import React from 'react';
import writeXlsxFile from 'write-excel-file';
import { for_obj, loc, Kup, is_empty, obj_str, cline, Btn } from 'sui';

const save_xlsx = (row, name, umd) => {
    writeXlsxFile(row, {fileName: name})
        .then(v => umd.endWait());
};

const export_xlsx = (data, col, fname, umd, ext) => {
    umd.startWait();

    if (is_empty(data)) {
        umd.setErr(loc("l_276"));
        return;
    }

    const h = col.map(d => {
        return {value: d};
    });

    const row = [h];

    if (!is_empty(ext)) {
        ext.forEach(d => {
            const tmp = [];
            col.forEach(t => tmp.push({value: obj_str(d, t)}));
            row.push(tmp);
        });
    }

    data.forEach(d => {
        const tmp = [];
        col.forEach(t => tmp.push({value: obj_str(d, t)}));
        row.push(tmp);
    });

    save_xlsx(row, `${fname}.xlsx`, umd);
};

const KFileUI = ({ himport, hout, htmpl, disabled, color="blue", lin=loc("l_344"), lout=loc("l_519"), no_acc_out, no_acc_in }) => {
    const getOut = () => {
        if (hout) {
            return <Btn color={color} hcmd={hout} className="ml-3" disabled={disabled || no_acc_out}>{lout}</Btn>;
        }

        return null;
    };

    const getTmpl = () => {
        if (htmpl) {
            return <Btn color={color} hcmd={htmpl} className="mr-3" disabled={disabled || no_acc_in}>{loc("l_628")}</Btn>;
        }

        return null;
    };

    const getIn = () => {
        if (himport) {
            return <Kup color={color} label={lin} hcmd={(v) => himport(v)} path={`/${cline()}/tmp`} disabled={disabled || no_acc_in}/>;
        }

        return null;
    };

    return (
        <div className="inline-flex">
            {getTmpl()}
            {getIn()}
            {getOut()}
        </div>
    );
};

/* col: [
 *  {...}
 * ]
 *
 * row: template's row
*/
const KFile = ({ umd, col, color="blue", title, row, hcmd, ext, out=true, tmpl=true, disabled,
    lin=loc("l_344"), lout=loc("l_519"), no_acc_out, no_acc_in }) => {
        const hTemp = () => {
            export_xlsx(row, col, `${title}_${loc("l_628")}`, umd);
        };

        const hExport = () => {
            export_xlsx(umd.value, col, title, umd, ext);
        };

        const hImport = (v) => {
            if (!v) {
                return;
            }

            const data = v["data"];
            if (is_empty(data)) {
                return;
            }

            umd.startWait();

            const head = data[0];
            const ret = [];

            for (let i = 1; i < data.length; i++) {
                const d = data[i];
                let tmp = {};

                head.forEach((t, j) => tmp[t] = d[j]);

                ret.push(tmp);
            }

            hcmd(ret);
        };

        return <KFileUI himport={hcmd ? hImport : null} hout={out ? hExport : null} htmpl={tmpl ? hTemp : null}
                        disabled={disabled} color={color} lin={lin} lout={lout} no_acc_out={no_acc_out} no_acc_in={no_acc_in}/>;
    };

const save_data = (data, coldata, fname, umd) => {
    umd.startWait();

    if (is_empty(data)) {
        umd.setErr(loc("l_276"));
        return;
    }

    const col = coldata.filter(d => d.key !== "e_opt");

    const h = col.map(d => {
        return {value: d.name};
    });

    const row = [h];

    data.forEach(d => {
        const tmp = [];
        col.forEach(t => {
            const k = t.key;
            let v = obj_str(d, k);

            tmp.push({value: v});
        });
        row.push(tmp);
    });

    save_xlsx(row, `${fname}.xlsx`, umd);
};

const adjust_val = (d, suf=false) => {
    const to_10 = (v) => {
        let tmp = parseFloat(v) * 10;
        tmp = Math.round(tmp);
        tmp /= 10;
        return tmp;
    };

    for_obj(d, (k, v) => {
        if (k.endsWith("dia")) {
            v = parseFloat(v);
            if (suf) {
                v = to_10(v);
            } else {
                v = Math.trunc(v);
            }
        } else if (k === "standout" || k === "dent" || k.endsWith("width") || k.endsWith("dt")) {
            v = parseFloat(v);
            if (suf) {
                v = to_10(v);
            } else {
                v = Math.round(v);
            }
        } else if (k === "angle") {
            v = parseFloat(v) * 100;
            v = Math.round(v);
            v /= 100;
        }

        d[k] = v;
    });
};

export {KFileUI, save_data, adjust_val, save_xlsx, export_xlsx, KFile};
